<template>
  <div class="config">
    <!-- 填报项 -->
    <div
      class="configItem"
      v-for="(data, index) in configItemList"
      :key="index"
    >
      <!-- 填报标题 -->
      <div class="itemTitle">
        <div></div>
        <span>{{ data.title }}</span>
      </div>
      <!-- 路径选择 -->
      <div class="itemContent">
        <button @click="itemClick">{{ data.buttonText }}</button>
        <input
          type="file"
          id="fileInput"
          :accept="data.acceptType"
          @change="handleFolderSelection(data)"
        />
        <br />
        <p>当前路径：</p>
        <input type="text" class="result" v-model="data.value" />
      </div>
    </div>
    <!-- 更新项 -->
    <div class="renewItem" v-show="false">
      <!-- 更新文件夹路径 -->
      <div class="renewPath">
        <div class="itemTitle">
          <div></div>
          <span>更新包路径</span>
        </div>
        <!-- 路径选择 -->
        <div class="itemContent">
          <button @click="itemClick">+选择更新包中的标识文件</button>
          <input
            type="file"
            id="fileInput"
            accept=".flag"
            @change="handleRenewFolder(data)"
          />
          <br />
          <p>当前路径：</p>
          <input type="text" class="result" v-model="renewPath" />
        </div>
      </div>
      <!-- 更新内容栏 -->
      <div class="renewContentList" v-show="isContentVisible">
        <div class="controller">
          <span>更新内容如下：</span>
          <div class="confirm" @click="renewRun">确认更新</div>
        </div>
        <div class="contentContainer">
          <div
            class="content"
            v-for="(data, index) in renewContent"
            :key="index"
            v-show="data.itemList.length > 0"
          >
            <!-- 标题 -->
            <div class="contentTitle">
              <img :src="require('@/assets/icon/' + data.pic + '.png')" />
              <span>{{ data.name }}</span>
            </div>
            <!-- 内容 -->
            <div
              class="contentList"
              v-for="(content, index1) in data.itemList"
              :key="index1"
            >
              <div @click="renewContetentPreview(data, index1)">
                {{ content }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 更新内容展示框 -->
    <div class="picContainer" v-show="picShow">
      <div class="closeButton" @click="picShow = false">×</div>
      <div class="pic">
        <img :src="picUrl" />
      </div>
    </div>
  </div>
</template>
      
<script>
/*eslint-disable*/
import { getCurrentInstance, onMounted } from "vue";
import { ElMessage } from "element-plus";
import mainApi from "@/api/mainApi.js";
import renewApi from "@/api/renewApi.js";
import pubsub from "pubsub-js";

export default {
  name: "配置项",
  data() {
    return {
      // 拼接json路径
      jsonPath: window.myApi.path.join(
        window.myApi.dirName,
        "../store/navigation.json"
      ),
      // 文件导航json
      navigationJson: {},
      // 配置项列表
      configItemList: [
        {
          title: "文件仓库路径",
          nickName: "fileHouse",
          value: "",
          buttonText: "+选择标识文件",
          acceptType: ".flag",
        },
        {
          title: "waigua路径",
          nickName: "waigua",
          value: "",
          buttonText: "+选择waigua中的一个文件",
          acceptType: "*/*",
        },
      ],
      // 更新包路径
      renewPath: "",
      // 更新内容
      renewContent: [
        {
          pic: "face-0",
          name: "面补",
          itemList: [],
        },
        {
          pic: "court-0",
          name: "地板",
          itemList: [],
        },
        {
          pic: "jersey-0",
          name: "球衣",
          itemList: [],
        },
        {
          pic: "scoreborad-0",
          name: "记分牌",
          itemList: [],
        },
        {
          pic: "packing-0",
          name: "整合包",
          itemList: [],
        },
      ],
      // 更新显隐
      isContentVisible: false,
      // 图片显隐
      picShow: false,
      // 图片预览
      picUrl: "",
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();

    onMounted(() => {
      // 读取现有路径
      readJson();
    });

    // 读取导航JSON
    function readJson() {
      mainApi.readJson(ElMessage, (data) => {
        // 将 JSON 字符串解析为 JavaScript 对象
        proxy.navigationJson = data;
        // 将json对象读入dom
        for (const key in proxy.navigationJson) {
          proxy.configItemList.forEach((item) => {
            if (item.nickName === key) {
              item.value = proxy.navigationJson[key];
            }
          });
        }
      });
    }

    // 更新包内容预览
    function renewContetentPreview(modList, index) {
      let fs = window.myApi.fs;
      let path = window.myApi.path;

      // mod文件夹路径
      let folderPath = "";
      let folderName = modList.itemList[index];
      if (modList.pic.split("-")[0] === "face") {
        // 面补特殊处理
        folderPath = path.join(
          proxy.renewPath,
          "face",
          folderName.split("-")[0],
          folderName
        );
      } else {
        folderPath = path.join(
          proxy.renewPath,
          modList.pic.split("-")[0],
          folderName
        );
      }
      // console.log(folderPath);
      // 图片路径
      let picPath = path.join(
        folderPath,
        "preview",
        fs.readdirSync(path.join(folderPath, "preview"))[0]
      );
      console.log(picPath);
      // 读取图片为base64
      fs.readFile(picPath, { encoding: "base64" }, (err, imageData) => {
        // 错误处理
        if (err) {
          ElMessage({
            message: `[${folderName}]预览图读取失败`,
            type: "error",
          });
          mainApi.writeDailyLog(
            ` ${folderName}图片读取失败:` + picPath + "--setup.vue"
          );
          throw err;
        }
        // 开启显示
        proxy.picShow = true;

        // 载入内容
        proxy.picUrl = `data:image/jpeg;base64,${imageData}`;
      });
    }

    return { renewContetentPreview };
  },
  methods: {
    handleFolderSelection(data) {
      console.log(event.target.files[0]);
      // 根据文件读取上一级路径
      data.value = window.myApi.path.join(event.target.files[0].path, "../");
      // 重写json对象
      this.navigationJson[data.nickName] = data.value;
      console.log(this.navigationJson);
      // 写入json文件
      window.myApi.fs.writeFile(
        window.myApi.jsonPath,
        JSON.stringify(this.navigationJson, null, 2),
        "utf8",
        (err) => {
          if (err) {
            ElMessage({
              message: "写入失败" + err,
              type: "error",
              duration: 10000,
            });
          } else {
            ElMessage("路径选择成功");
          }
        }
      );
    },
    itemClick() {
      event.target.nextSibling.click();
    },
    // 选择更新包路径
    handleRenewFolder() {
      let fs = window.myApi.fs;
      let path = window.myApi.path;

      // 获取路径
      this.renewPath = path.join(event.target.files[0].path, "../");

      // 展示文件
      this.renewContent.forEach((element) => {
        // 路径拼接
        let folderPath = path.join(this.renewPath, element.pic.split("-")[0]);
        // 检验是否存在
        if (!fs.existsSync(folderPath)) return;
        // 填入文件名称
        if (path.basename(folderPath) === "face") {
          // 面补类型特殊处理
          let folderList = fs.readdirSync(folderPath);
          let faceList = [];
          for (const folder of folderList) {
            faceList.push(...fs.readdirSync(path.join(folderPath, folder)));
          }
          element.itemList = faceList;
        } else {
          // 其余类型
          element.itemList = fs.readdirSync(folderPath);
        }
      });
    },
    // 执行更新
    async renewRun() {
      try {
        for (const element of this.renewContent) {
          const folderPath = window.myApi.path.join(
            this.renewPath,
            element.pic.split("-")[0]
          );
          if (!window.myApi.fs.existsSync(folderPath)) continue; // 跳过不存在路径

          if (element.pic.split("-")[0] === "face") {
            // 等待异步操作完成
            await renewApi.faceRenew(this.configItemList[0].value, folderPath);
          } else {
            // 其他类型同样按顺序执行
            await renewApi.commonRenew(
              this.configItemList[0].value,
              folderPath
            );
          }
        }
      } catch (error) {
        console.error("更新操作失败:", error);
        ElMessage.error(`更新操作失败: ${error.message}`);
      }
    },
  },
  watch: {
    // 监听 renewContent 的变化
    renewContent: {
      deep: true,
      handler() {
        this.isContentVisible = this.renewContent.some(
          (data) => data.itemList.length > 0
        );
      },
    },
  },
};
</script>
      
<style lang="less" scoped>
@import "../less/variables.less";
.configItem,
.renewPath {
  // border: @border;
  padding: 0.5% 2%;
  font-size: 110%;

  > .itemTitle {
    display: flex;
    align-items: center;
    font-weight: bold;
    margin-bottom: 1%;
    > div {
      width: 5px;
      height: 20px;
      background-color: @red;
      border-radius: 5px;
      margin-right: 0.5%;
    }
  }
  > .itemContent {
    > #fileInput {
      display: none;
    }
    > button {
      background-color: transparent;
      outline: none;
      border: 0px;
      background-color: #fc3d49;
      color: white;
      border-radius: 5px;
      padding: 0.5% 1%;
      margin-bottom: 1%;
    }
    > button:hover {
      font-weight: bold;
    }
    > p {
      font-size: 80%;
      color: #555555;
      display: inline-block;
    }
    > .result {
      display: inline-block;
      border: #b4b4b4 1px solid;
      box-shadow: @box-shadow;
      outline: none;
      background-color: transparent;
      font-size: 90%;
      padding: 1% 1.5%;
      color: #5d5d5d;
      width: 50%;
      border-radius: 5px;
    }
  }
}
.renewContentList {
  padding: 0% 2%;
  > .controller {
    margin: 1% 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    > .confirm {
      border: @border;
      border-radius: 5px;
      padding: 5px 10px;
      color: @red;
      font-size: 90%;
    }
    > .confirm:hover {
      cursor: pointer;
    }
  }
  > .contentContainer {
    display: flex;
    > .content {
      // border: @border;
      flex: 1;
      > .contentTitle {
        display: flex;
        align-items: center;
        font-weight: bold;
        > img {
          width: 25px;
          margin-right: 2%;
        }
      }
      > .contentList {
        margin-left: 30px;
        > * {
          margin: 2% 0;
        }
        > div:hover {
          cursor: pointer;
          color: @red;
        }
      }
    }
  }
}
.picContainer {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  > .closeButton {
    position: absolute;
    z-index: 999;
    color: white;
    background-color: @red;
    border-radius: 5px;
    padding: 5px 7px;
    top: 2%;
    right: 1%;
  }
  > .closeButton:hover {
    cursor: pointer;
  }
  > .pic > img {
    max-width: 700px;
    border-radius: 5px;
    box-shadow: @box-shadow;
  }
}
</style>
      